<template>
  <div class="edit">
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      @submit.native.prevent="onSubmit"
    >
      <el-form-item label="名称">
        <el-input
          v-model="form.name"
          v-focus
          id="name"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-upload
          class="avatar-uploader"
          action="http://localhost:3000/api/admin/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="form.icon"
            :src="form.icon"
            class="avatar"
          >
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
          ></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          native-type="submit"
        >保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    id: {}
  },
  data: () => ({
    form: {
      name: '',
      icon: ''
    }
  }),
  created() {
    // console.log(this.id)
    this.id && this.getHeroById()
  },
  methods: {
    handleAvatarSuccess(res) {
      // console.log(res)
      this.form.icon = res.url
      // this.$set(this.form, 'icon', res.url)
    },
    async onSubmit() {

      let res

      if (!this.id) {
        res = await this.$http.post('/heros', this.form)
        // console.log(res)
        this.$message({
          message: '英雄添加成功',
          type: 'success'
        });
        this.$router.push('/hero/list')
      } else {
        res = await this.$http.put(`/heros/${this.id}`, this.form)
        // console.log(res)
        this.$message({
          message: '英雄编辑成功',
          type: 'success'
        });
        this.$router.push('/hero/list')
      }
    },
    async getHeroById() {
      const res = await this.$http.get('/heros/' + this.id)
      this.form = res.data.message
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.querySelector('input').focus()
      }
    }
  }
}
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon-plus.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>